<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once APPPATH . 'controllers/main.php';

/**
 * Контроллер просмотра видео
 *
 * @package CoreFramework
 * @version 1.0
 * @author Gennadiy Kozlenko
 */
class Video extends Main {
   
   /**
    * Идентификатор видео
    *
    * @var int
    */
   var $_id_video = 0;
   
   /**
    * Конструктор класса
    *
    * @access public
    * @return Video
    */
   function Video() {
      parent::Main();
      if (false !== $this->input->get('id')) {
         $this->_id_video = (int) $this->input->get('id');
      }
      $this->load->language('video');
      $this->set_layout('video');
      $this->load->config('parser');
   } // end Video
   
   /**
    * Метод по умолчанию
    *
    * @access public
    */
   function index() {
      $data = array();
      
      $this->load->model('m_video');
      $this->m_video->set_id($this->_id_video);
      if ('random' != $this->get_method() && (0 == $this->m_video->get_id('id_video') || 'active' != $this->m_video->get('status') || 0 == $this->m_video->get('num_torrents'))) {
         show_404();
      }
      
      // Комментирование
      $author = '';
      $email = '';
      $comment = '';
      if (false !== $this->input->post('post')) {
         $author = trim($this->input->post('author'));
         $email = trim($this->input->post('email'));
         $comment = trim($this->input->post('comment'));
         
         $this->load->library('validation');
         $rules = array(
            'author'  => 'trim|required|max_length[100]',
            'email'   => 'trim|required|valid_email|max_length[100]',
            'comment' => 'trim|required|max_length[4096]',
            'captcha' => 'trim|required|callback_check_captcha'
         );
         $this->validation->set_rules($rules);
         if ($this->validation->run()) {
            $this->load->model('m_comment');
            $this->m_comment->set('id_video', $this->_id_video);
            $this->m_comment->set('author', $author);
            $this->m_comment->set('email', $email);
            $this->m_comment->set('comment', $comment);
            $this->m_comment->set('status', 'active');
            $this->m_comment->set('date_created', mdate('%Y-%m-%d %H:%i:%s'));
            if ($this->m_comment->update()) {
               $this->set_message($this->lang->line('comment_send_succ'), 'info', true);
               $this->redirect('video', 'index', array('id' => $this->_id_video));
            }
         }
      }
      $data['author_value'] = htmlspecialchars($author);
      $data['email_value'] = htmlspecialchars($email);
      $data['comment_value'] = htmlspecialchars($comment);
      
      $video = $this->m_video->get_fields();
      $video['title_encoded'] = htmlspecialchars($video['title']);
      $video['title_urlencoded'] = urlencode($video['title']);
      $video['orig_title_encoded'] = htmlspecialchars($video['orig_title']);
      $video['orig_title_urlencoded'] = urlencode($video['orig_title']);
      $video['year_encoded'] = htmlspecialchars($video['year']);
      $video['year_urlencoded'] = urlencode($video['year']);
      
      // Download link
      $video['download_link'] = $this->m_video->getPartnerDownloadLink();
      
      // Online link
      $video['online_link'] = $this->m_video->getPartnerOnlineLink();
      if (!empty($video['online_link'])) {
          $video['trailer'] = '';
      }
      
      // Обрабатываем description
      $this->load->helper('content');
      $video['description'] = get_abstract(stripslashes($video['description']), 500);
      
      unset($video['date_created']);
      if (!empty($video['year'])) {
         $video['year'] = anchor(create_link('year', $video['year']), $video['year']);
      }
      
      // Image
      if (!empty($video['image'])) {
         $this->load->helper('thumbnail');
         $video['image'] = base_url() . create_thumbnail($video['image'], 150, 200);
      } else {
         $video['image'] = base_url() . 'images/no_image.jpg';
      }
      
      // Get genres
      $genres = array();
      foreach ($this->m_video->get_genres() as $genre) {
         $value = anchor(create_link('genre', $genre['slug']), $genre['title']);
         array_push($genres, $value);
      }
      $video['genres'] = implode('&nbsp; | &nbsp;', $genres);
      
      // Get countries
      $countries = array();
      foreach ($this->m_video->get_countries() as $country) {
         $value = anchor(create_link('country', $country['slug']), $country['title']);
         array_push($countries, $value);
      }
      $video['countries'] = implode('&nbsp; | &nbsp;', $countries);
      
      // Get actors
      $actors = array();
      foreach ($this->m_video->get_actors() as $actor) {
         $value = anchor(create_link('actor', $actor['slug']), $actor['title']);
         array_push($actors, $value);
      }
      $video['actors'] = implode('<br />', $actors);
      
      // Get directors
      $directors = array();
      foreach ($this->m_video->get_directors() as $director) {
         $value = anchor(create_link('director', $director['slug']), $director['title']);
         array_push($directors, $value);
      }
      $video['directors'] = implode('<br />', $directors);
      
      // Get rating
      $video['rating'] = sprintf('%.1f', $this->m_video->get_rating());
      
      // Get comments
      $comments = $this->m_video->get_comments();
      foreach ($comments as $id => $comment) {
         $comment['email_hash'] = md5($comment['email']);
         $date = new DateTime($comment['date_created']);
         $comment['date_created'] = $date->format('d.m.Y');
         foreach ($comment as $key => $val) {
            $comment[$key] = htmlspecialchars($val);
         }
         $comment['comment'] = nl2br($comment['comment']);
         $comments[$id] = $comment;
      }
      $video['comments'] = $comments;
      $video['count_comments'] = count($comments);
      
      $data['sid'] = md5(uniqid());
      $data['show_comments'] = 0 < count($comments) ? array(array()) : array();
      
      foreach ($video as $key => $val) {
         if (empty($val)) {
            $video['show_' . $key] = array();
         }
      }
      // Получаем продолжительность в минутах
      $length = substr($video['length'], 0, 2) * 60 + substr($video['length'], 3, 2);
      $video['length'] = $length;
      if (0 == $length) {
         $video['show_length'] = array();
      }
      
      $this->load->model('m_video_torrent');
      $torrents = $this->m_video->get_torrents();
      for ($i = 0; $i < count($torrents); $i++) {
         $torrent = $torrents[$i];
         $this->m_video_torrent->set_id($torrent['id_torrent']);
         $stats = $this->m_video_torrent->get_stats();
         $torrent['show_stats'] = array();
         $torrent['seeders'] = 0;
         $torrent['leechers'] = 0;
         if (!empty($stats)) {
            $torrent['show_stats'] = array(array());
            $torrent['seeders'] = $stats['complete'];
            $torrent['leechers'] = $stats['incomplete'];
         }
         $torrent['torrent_title'] = $torrent['title'];
         if ($i == count($torrents) - 1) {
            $torrent['last'] = array(array());
         } else {
            $torrent['last'] = array();
         }
         foreach ($torrent as $key => $val) {
            if (empty($val)) {
               $torrent['show_' . $key] = array();
            }
         }
         if (!empty($torrent['video']) || !empty($torrent['video_codec'])) {
            $torrent['show_video'] = array(array());
         }
         if (!empty($torrent['audio']) || !empty($torrent['audio_codec'])) {
            $torrent['show_audio'] = array(array());
         }
         $screenshots = array();
         foreach ($torrent['screenshots'] as $image) {
             array_push($screenshots, array(
                 'torrent_screenshot_image' => $image
             ));
         }
         $torrent['torrent_screenshots'] = $screenshots;
         $torrent['show_torrent_screenshots'] = 0 < count($screenshots) ? array(array()) : array();
         $torrents[$i] = $torrent;
      }
      $video['torrents'] = $torrents;
      
      // screenshots
      $screenshots = $this->m_video->get_screenshots();
      foreach ($screenshots as $id => $screenshot) {
          $screenshots[$id]['screenshot_image'] = $screenshot['image'];
      }
      $video['screenshots'] = $screenshots;
      $video['show_screenshots'] = 0 < count($screenshots) ? array(array()) : array();
      
      $data['uid'] = $this->_id_video . md5(time()); //для идентификации статистики
      
      // SEO
      $this->load->helper('text');
      
      $title = $this->m_video->get('title');
      if ('' != $this->m_video->get('orig_title')) {
         $title .= ' / ' . $this->m_video->get('orig_title');
      }
      if (0 < $this->m_video->get('year')) {
         $title .= ' (' . $this->m_video->get('year') . ')';
      }


      $this->set_metadata('video', $this->m_video->get('title'));
      
      $description = trim(strip_tags(stripslashes($this->m_video->get('description'))));
      $description = $title . '. ' . $description;
      $description = character_limiter($description, 160, '');
      $this->set_description(htmlspecialchars($description));
      
      $this->add_keyword(htmlspecialchars(mb_strtolower($this->m_video->get('title'), 'utf-8')));
      if ('' != $this->m_video->get('orig_title')) {
         $this->add_keyword(htmlspecialchars(mb_strtolower($this->m_video->get('orig_title'), 'utf-8')));
      }
                  
      $data = array_merge($data, $video);
      $this->set_content($this->parser->parse('video/card.html', $data, true));
      
      $this->display();
   } // end index
   
   /**
    * Метод генерирования и отображения каптчи
    *
    * @access public
    */
   function captcha() {
      $this->load->library('captcha');
      $this->captcha->set_width(167);
      $this->captcha->set_height(45);
      $this->captcha->set_length(6);
      $this->captcha->display();
   } // end captcha
   
   /**
    * Функция валидирования каптчи
    *
    * @access public
    * @param string $str
    * @return boolean
    */
   function check_captcha($str) {
      $this->load->library('captcha');
      return $this->captcha->valid_captcha($str);
   } // end check_captcha
   
   /**
    * Установка рейтинга
    *
    */
   function rate() {
      $this->load->model('m_video');
      $this->m_video->set_id($this->_id_video);
      
      $rating = (int) $this->input->post('rating');
      $ip_address = $this->input->ip_address();
      if (0 < $rating) {
         // Получаем уид пользователя
         $uid = '';
         if (false !== $this->input->cookie('uid')) {
            $uid = $this->input->cookie('uid');
         } else {
            $uid = md5(uniqid());
            $this->load->helper('cookie');
            set_cookie('uid', $uid, 86400 * 30 * 12 * 10);
         }
         $this->m_video->rate($rating, $ip_address, $uid);
      }
      $this->set_layout('empty');
      $this->set_content($this->m_video->get_rating());
      
      $this->display();
   }
   
   /**
    * Переход на сайт скачки видео
    */
   function download() {
      $this->load->model('m_video');
      $this->m_video->set_id($this->_id_video);
      $video = $this->m_video->get_fields();
      $download_link = $this->m_video->getPartnerDownloadLink();
      $this->go($download_link);
   }
   
}
